import { getToken, setToken, removeToken ,setAllToken,getAllToken} from '@/utils/auth'
import {getShopProductNum ,getCartList ,addToCart,shoppChangeNum,shoppDeleteCart} from '@/api/index'

const shop = {
  state: {
   shopNum:Number(getAllToken("tabIndex")) || 0,
   shopList:JSON.parse(localStorage.getItem("shopList")) || [],
   shopMap:JSON.parse(localStorage.getItem("shopMap")) ||{},
   totalShopNum: localStorage.getItem("totalShopNum") || 0,
  },
  mutations: {
    INIT_SHOPLIST: (state, list) => {
      state.shopList = list.checkShoppingCartNoticeDTO.cartInfoList.concat(list.cartInfoList);
      // state.totalShopNum = list.length;
    },
    INIT_SHOPLIST1: (state, item) => {
      // state.totalShopNum = list.length;
    },
    INIT_SHOPMAP1: (state, item) => {
      // eslint-disable-next-line no-prototype-builtins
      if(state.shopMap.hasOwnProperty((item.activityProductNo).toString())){
        state.shopMap[item.activityProductNo] = (Number(state.shopMap[item.activityProductNo])+1).toString();
        state.shopList.map((i,index)=>{
          if(i.activityProductNo == item.activityProductNo){
            i.quantity = Number(i.quantity)+1;
            i.isChecked = 1;
            return;
          }
        })
      }else{
        let obj = Object.assign({isChecked:1,quantity:1},item);
        state.shopMap[item.activityProductNo] = '1';
        state.shopList.push(obj);
      }
      let count =0;
      for (let k in state.shopMap) {
        count += Number(state.shopMap[k]);
      }
      state.totalShopNum = count;
      localStorage.setItem("shopList",JSON.stringify(state.shopList));
      localStorage.setItem("shopMap",JSON.stringify(state.shopMap));
      localStorage.setItem("totalShopNum",state.totalShopNum);
      // state.shopList.push(item);
      // state.totalShopNum = list.length;
    },
    INIT_SHOPMAP: (state, obj) => {
      state.shopMap = obj;
      let count =0;
      for (let k in obj) {
        // console.log(k,111)
        count += Number(obj[k]);
      }
      state.totalShopNum = count;
    },
    ADD_SHOPNUM: (state, goodsInfo) => {
      state.shopNum ++;
      state.shopList.push(goodsInfo);
    },
    REDUCE_SHOPNUM: (state, item) => {
      // eslint-disable-next-line no-prototype-builtins
      if(state.shopMap.hasOwnProperty((item.activityProductNo).toString())){
        state.shopMap[item.activityProductNo] = (Number(state.shopMap[item.activityProductNo])-1).toString();
        state.shopList.map((i,index)=>{
          if(i.activityProductNo == item.activityProductNo){
            i.quantity = Number(i.quantity)-1;
            return;
          }
        })
      }else{
        let obj = Object.assign({isChecked:1,quantity:1},item);
        state.shopMap[item.activityProductNo] = '1';
        state.shopList.push(obj);
      }
      let count =0;
      for (let k in state.shopMap) {
        count += Number(state.shopMap[k]);
      }
      state.totalShopNum = count;
      localStorage.setItem("shopList",JSON.stringify(state.shopList));
    },
    DELETE_SHOP: (state, item) => {
      delete state.shopMap[item.activityProductNo];
      let count =0;
      for (let k in state.shopMap) {
        count += Number(state.shopMap[k]);
      }
      state.totalShopNum = count;
      localStorage.setItem("totalShopNum",state.totalShopNum);
      localStorage.setItem("shopMap",JSON.stringify(state.shopMap));
    },
    INIT_LOGINOUT: (state, item) =>{
        state.shopList = [];
        state.shopMap = {};
        state.totalShopNum =0;
    }
  },
  actions: {
    loginout({ commit },val){
      commit('INIT_LOGINOUT', val);
    },
    // 初始化购物车列表
    init({ commit },memberNo){
      return new Promise((resolve, reject) => {
        let para ={'memberNo':memberNo}
        getCartList(para).then(response => {
            const data = response.data;
            if(data.code == "000"){
              commit('INIT_SHOPLIST', data.content);
            }
            resolve(data)
            
          }).catch(error => {
            reject(error)
          })
      })
    },
    // 初始化购物车数量
    initMap({ commit },memberNo){
      return new Promise((resolve, reject) => {
        let para ={'memberNo':memberNo}
        getShopProductNum(para).then(response => {
          const data = response.data;
          if(data.code == "000"){
            commit('INIT_SHOPMAP', data.content);
          }
          resolve(data.content)
          
        }).catch(error => {
          reject(error)
        });
      })
    },
    addShop({ dispatch,commit },item){
      return new Promise((resolve, reject) => {
        let obj = {'activityProductNo':item.activityProductNo,"isChecked":"1","quantity":"1",'promotionNo':item.promotionNo,'promotionType':item.promotionType};
        if(getAllToken("memberNo")){ //判断用户信息存在
          //调用api
            let list=[];
            list.push(obj)
            let para ={'memberNo':getAllToken("memberNo"),'addCartDTOList':list};
            addToCart(para).then(response => {
                const data = response.data;
                if(data.code == "000"){
                //   resolve(data)
                  dispatch('initMap',getAllToken("memberNo"));
                 
                }
                resolve(data)
                
              }).catch(error => {
                reject(error)
            });
        }else{
          // 设置全局缓存 ，新增存储购物车数量和购物车商品列表
          commit('INIT_SHOPLIST1', item);
          commit('INIT_SHOPMAP1', item);
          resolve("000")
        }
      })
     
    },
    addShop1({ dispatch,commit },item){
      return new Promise((resolve, reject) => {
        let obj = {'activityProductNo':item.activityProductNo,"isChecked":"1","quantity":(Number(item.quantity)+1)}
        if(getAllToken("memberNo")){ //判断用户信息存在
          //调用api
            let para ={'memberNo':getAllToken("memberNo"),'activityProductNo':item.activityProductNo,"quantity":(Number(item.quantity)+1)};
            shoppChangeNum(para).then(response => {
                const data = response.data;
                if(data.code == "000"){
                  dispatch("initMap",getAllToken("memberNo"));
                  resolve(data)
                }
              }).catch(error => {
                reject(error)
            });
        }else{
          // 设置全局缓存 ，新增存储购物车数量和购物车商品列表
          commit('INIT_SHOPLIST1', item);
          commit('INIT_SHOPMAP1', item);
        }
      })
     
    },
    reduceShopNum({ dispatch,commit },item) {
      return new Promise((resolve, reject) => {
        let obj = {'activityProductNo':item.activityProductNo,"isChecked":"1","quantity":(Number(item.quantity)-1)}
        if(getAllToken("memberNo")){ //判断用户信息存在
          //调用api
            let para ={'memberNo':getAllToken("memberNo"),'activityProductNo':item.activityProductNo,"quantity":(Number(item.quantity)-1)};
            shoppChangeNum(para).then(response => {
                const data = response.data;
                if(data.code == "000"){
                  dispatch("initMap",getAllToken("memberNo"));
                  resolve(data)
                }
              }).catch(error => {
                reject(error)
            });
        }else{
          // 设置全局缓存 ，新增存储购物车数量和购物车商品列表
          commit('REDUCE_SHOPNUM', item);
        }
      })
      
    },
    
    addShopNum({ commit },goodsInfo) {
      if(getAllToken("memberNo")){ //判断用户信息存在
        //调用api
      }else{
        // 设置全局缓存 ，新增存储购物车数量和购物车商品列表
        // eslint-disable-next-line no-undef
        commit('ADD_SHOPNUM',item)
      }
     
    },
    
    deleteShop({ dispatch,commit },list){
      return new Promise((resolve, reject) => {
        if(getAllToken("memberNo")){ //判断用户信息存在
          //调用api
          let deleteCartProNoList = [];
          list.map((item,index)=>{
            if(item.isChecked == 1 || item.shelveStatus == 2){
              deleteCartProNoList.push(item.activityProductNo);
            }
          })
            let para ={'memberNo':getAllToken("memberNo"),'deleteCartProNoList':deleteCartProNoList};
            shoppDeleteCart(para).then(response => {
                const data = response.data;
                if(data.code == "000"){
                  dispatch('initMap',getAllToken("memberNo"));
                  resolve(data);
                }
              }).catch(error => {
                reject(error)
            });
        }else{
          // 设置全局缓存 ，新增存储购物车数量和购物车商品列表
          // list.map((item,index)=>{
          //   console.log(item.isChecked == 1 || item.isChecked,"delete")
          //   if(item.isChecked == 1 || item.isChecked){
          //     console.log(item,"delete")
          //     list.splice(index,1);
          //     commit('DELETE_SHOP',item);
          //   }
          // })
          for(var i=0;i<list.length;i++){
            if(list[i].isChecked == 1 || list[i].isChecked){

              // console.log(list[i],"delete");
              commit('DELETE_SHOP',list[i]);
              list.splice(i,1);
              
              // console.log(i)
              i--;
              // console.log(i)
              if(i == 0){
                return
              }
              
            }
          }
          localStorage.setItem("shopList",JSON.stringify(list));
          resolve(list)
        }
      })
      
    }
  }
}

export default shop
